﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Collections;
using Newtonsoft.Json;
using System.Xml.Linq;
using System.Xml;

namespace curbside.Core.Utility.Convert
{
    public class ConvertHelper
    {
        /// <summary>
        /// 将IList<Hashtable>转换成datatable
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable ListHashtableToDataTable(IList<Hashtable> list)
        {
            if (list == null || list.Count == 0)
                return null;

            DataTable dt = new DataTable();
            Hashtable ht = list[0];
            int colnum = ht.Keys.Count;
            List<string> keys = new List<string>();
            foreach (string key in ht.Keys)
            {
                dt.Columns.Add(key, ht[key].GetType());
                keys.Add(key);
            }

            foreach (Hashtable var in list)
            {
                DataRow row = dt.NewRow();
                foreach (string key in var.Keys)
                {
                    row[key] = var[key];
                }

                dt.Rows.Add(row);
            }

            return dt;
        }

        /// <summary>
        /// 将字符串转换为指定Type类型
        /// </summary>
        /// <param name="type"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static object ToType(Type type, string value)
        {
            return System.ComponentModel.TypeDescriptor.GetConverter(type).ConvertFrom(value);
        }

        /// <summary>
        /// 将十进制数字number转换为n进制并存储在List数组中
        /// </summary>
        /// <param name="number"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static List<long> DigitConvert(long number, int n)
        {
            List<long> list = new List<long>();

            long x = number / n;
            long y = number % n;

            list.Add(y);

            while (x > n)
            {
                number = x;
                x = number / n;
                y = number % n;

                list.Add(y);
            }

            list.Add(x);
            list.Reverse();
            return list;
        }

        /// <summary>
        /// 将十进制数字转换为36进制编码的字符
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static string DigitToString(long number)
        {
            char[] array = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();

            StringBuilder sb = new StringBuilder();
            foreach (long item in DigitConvert(number, array.Length))
            {
                sb.Append(array[item]);
            }

            return sb.ToString();
        }
    }
}
